package com.android.infantschool.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.infantschool.R;
import com.android.infantschool.bean.BaseBean;
import com.android.infantschool.bean.BindingQrCodeBean;
import com.android.infantschool.bean.ParentsBindingBean;
import com.android.infantschool.model.config.AppConfig;
import com.android.infantschool.model.config.AppDataSource;
import com.android.infantschool.model.mvp.presenter.BabyBindingQrCodePresenter;
import com.android.infantschool.model.mvp.presenter.BabyBindingQrCodePresenterImpl;
import com.android.infantschool.model.mvp.presenter.ParentsListPresenter;
import com.android.infantschool.model.mvp.presenter.ParentsListPresenterImpl;
import com.android.infantschool.model.mvp.view.BabyBindingQrCodeView;
import com.android.infantschool.model.mvp.view.ParentsListView;
import com.android.infantschool.ui.adapter.ParentsBindingAdapter;
import com.android.infantschool.ui.dialog.DialogParentsBinding;
import com.android.infantschool.util.ToastUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ParentsBindingActivity extends BaseActivity implements ParentsBindingAdapter.OnLister, OnRefreshListener, OnLoadMoreListener, ParentsListView, BabyBindingQrCodeView {

    @BindView(R.id.img_back)
    public ImageView imgBack;
    @BindView(R.id.title)
    public RelativeLayout rlTitle;
    @BindView(R.id.tv_title)
    public TextView tvTitle;
    @BindView(R.id.recyclerView)
    public RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    public SmartRefreshLayout refreshLayout;
    public ParentsBindingAdapter adapter;
    private ParentsListPresenter listPresenter = null;
    private BabyBindingQrCodePresenter qrCodePresenter = null;
    private int pageNum = 0;//总页数
    private int pageNow = 1;//当前请求的第几页
    private boolean isRefresh = false;//false:刷新  true:加载

    public static Intent newIntent(Activity activity) {
        Intent intent = new Intent(activity, ParentsBindingActivity.class);
        return intent;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_parents_binding);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        listPresenter = new ParentsListPresenterImpl(this);
        qrCodePresenter = new BabyBindingQrCodePresenterImpl(this);
        rlTitle.setPadding(0, this.height, 0, 0);
        tvTitle.setText("家长绑定");

        adapter = new ParentsBindingAdapter(this, this);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        recyclerView.setAdapter(adapter);

        this.showLoading();
        isRefresh = false;
        pageNow = 1;
        getList(String.valueOf(pageNow));

        //设置 Footer 为 球脉冲 样式
        refreshLayout.setRefreshHeader(new ClassicsHeader(this));
        refreshLayout.setRefreshFooter(new ClassicsFooter(this));
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);
    }

    /**
     * @param page
     */
    private void getList(String page) {
        Map<String, String> map = new HashMap<>();
        map.put("token", AppConfig.getToken());
        map.put("CountPerpage", "10");//页条数
        map.put("CurentPageIndex", page);//第几页
        Log.e(TAG, "map:" + map.toString());
        listPresenter.getParentsList(map);
    }

    @Override
    public void lister(int position) {
        ParentsBindingBean.DataBean bindingBean = adapter.list.get(position);
        if (bindingBean.getBindingStatus() == 1) {//已绑定
            startActivity(ToViewBindingActivity.newIntent(this, bindingBean.getBabyName(), String.valueOf(bindingBean.getId())));
        } else {//未绑定
            this.showLoading();
            Map<String, String> map = new HashMap<>();
            map.put("token", AppConfig.getToken());
            map.put("babyId", String.valueOf(bindingBean.getId()));
            Log.e(TAG, "map:" + map.toString());
            qrCodePresenter.getBabyBindingQrCode(map);
        }
    }

    private DialogParentsBinding dialogParentsBinding = null;

    private void showParentsBindingDialog(String url) {
        dismissParentsBindingDialog();
        dialogParentsBinding = new DialogParentsBinding(this, url);
        dialogParentsBinding.show();
    }

    private void dismissParentsBindingDialog() {
        if (dialogParentsBinding != null) {
            dialogParentsBinding.dismiss();
            dialogParentsBinding.cancel();
            dialogParentsBinding = null;
        }
    }

    @Override
    public void errorParentsList(String error) {
        this.dismissLoading();
        refreshLayout.finishLoadMore(true);
        refreshLayout.finishRefresh(true);
        ToastUtil.showShortToast(this, "网络异常:" + error);
    }

    @Override
    public void successParentsList(BaseBean baseBean) {
        this.dismissLoading();
        refreshLayout.finishLoadMore(true);
        refreshLayout.finishRefresh(true);
        ParentsBindingBean bindingBean = (ParentsBindingBean) baseBean;
        if (bindingBean.getCode() == 0) {
            pageNum = bindingBean.getCount() / 5 + 1;//总条数
            if (isRefresh) {//加载
                adapter.addDataAll(bindingBean.getData());
            } else {//刷新
                adapter.setData(bindingBean.getData());
            }
            Log.e(TAG, "size:" + adapter.list.size());
        } else {
            ToastUtil.showShortToast(this, "获取失败:" + bindingBean.getMsg());
        }
    }

    @OnClick({R.id.img_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_back:
                this.finish();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (listPresenter != null) {
            listPresenter.onDestroy();
            listPresenter = null;
        }
        dismissParentsBindingDialog();
    }

    @Override
    public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
        isRefresh = false;
        pageNow = 1;
        getList(String.valueOf(pageNow));
    }

    @Override
    public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
        isRefresh = true;
        pageNow++;
        if (pageNow > pageNum) {//没有最新数据
            refreshLayout.finishLoadMore(true);
            refreshLayout.finishRefresh(true);
            return;
        }
        getList(String.valueOf(pageNow));
    }

    @Override
    public void errorBabyBindingQrCode(String error) {
        this.dismissLoading();
        ToastUtil.showShortToast(this, "网络异常:" + error);
    }

    @Override
    public void successBabyBindingQrCode(BaseBean baseBean) {
        this.dismissLoading();
        BindingQrCodeBean qrCodeBean = (BindingQrCodeBean) baseBean;
        if (qrCodeBean.getCode() == 0) {
            showParentsBindingDialog(qrCodeBean.getData());
        } else {
            ToastUtil.showShortToast(this, "获取失败:" + qrCodeBean.getMsg());
        }
    }
}